﻿$(document).ready(function () {
    $('.fr-searchparts').submit(function () {
        var serializedForm = $(this).serialize();
        App.blockUI($('.lstcb-parts'), false);
        $.ajax({
            type: 'POST',
            url: '/orderview/searchparts',
            data: serializedForm,
            success: function (data) {
                $(".lstcb-parts").html(data);
            },
            error: function () {
                alert('search fail!');
            }
        });
        return false;
    });

    $('.fr-addparttoorder').submit(function () {
        var qty = $("#qty").val();
        if (qty == 0) {
            alert('must be greater than 0!');
            return false;
        }
        var warehouseid = $("#warehouseID").val();
        var serializedForm = $(this).serialize();
        App.blockUI($('.tbl-order-items-parts'), false);
        $.ajax({
            type: 'POST',
            url: '/orderview/addpartstoorder',
            data: serializedForm + "&qty=" + qty + "&warehouseid=" + warehouseid,
            success: function (data) {
                $(".tbl-order-items-parts").html(data);
            }
        });
        return false;
    });

    $('.fr-addproducttoorder').submit(function () {
        var qty = $("#qty").val();
        if (qty == 0) {
            alert('must be greater than 0!');
            return false;
        }
        var warehouseid = $("#warehouseID").val();
        var serializedForm = $(this).serialize();
        App.blockUI($('.tbl-order-items-parts'), false);
        $.ajax({
            type: 'POST',
            url: '/orderview/addproducttoorder',
            data: serializedForm + "&qty=" + qty + "&warehouseid=" + warehouseid,
            success: function (data) {
                $(".tbl-order-items-parts").html(data);
            }
        });
        return false;
    });

    $('.fr-addpartstoordereditform').submit(function () {
        var qty = $("#qty").val();
        if (qty == 0) {
            alert('must be greater than 0!');
            return false;
        }
        var warehouseid = $("#warehouseID").val();
        var serializedForm = $(this).serialize();
        App.blockUI($('.tbl-order-items-parts'), false);
        $.ajax({
            type: 'POST',
            url: '/orderview/addpartstoordereditform',
            data: serializedForm + "&qty=" + qty + "&warehouseid=" + warehouseid,
            success: function (data) {
                $(".tbl-order-items-parts").html(data);
            }
        });
        return false;
    });
    
    $('.fr-addproducttoordereditform').submit(function () {
        var qty = $("#qty").val();
        if (qty == 0) {
            alert('must be greater than 0!');
            return false;
        }
        var warehouseid = $("#warehouseID").val();
        var serializedForm = $(this).serialize();
        App.blockUI($('.tbl-order-items-parts'), false);
        $.ajax({
            type: 'POST',
            url: '/orderview/addproducttoordereditform',
            data: serializedForm + "&qty=" + qty + "&warehouseid=" + warehouseid,
            success: function (data) {
                $(".tbl-order-items-parts").html(data);
            }
        });
        return false;
    });

    $('.fr-searchproduct').submit(function () {
        var serializedForm = $(this).serialize();
        App.blockUI($('.lstcb-product'), false);
        $.ajax({
            type: 'POST',
            url: '/orderview/searchproduct',
            data: serializedForm,
            success: function (data) {
                $(".lstcb-product").html(data);
            },
            error: function () {
                alert('search fail!');
            }
        });
        return false;
    });

    $('.fr-order-items-parts').submit(function () {
        if (confirm('Are you sure you want to remove selected part(s)?')) {
            var serializedForm = $(this).serialize();
            App.blockUI($('body'), true);
            var url = $('.fr-order-items-parts').attr('action');
            $.ajax({
                type: 'POST',
                url: url,
                cache: false,
                data: serializedForm,
                success: function (data) {
                    $(".tbl-order-items-parts").html(data);
                },
                error: function () {
                    alert('Remove error!');
                }
            });
            App.unblockUI($('body'));
            return false;
        } else {
            return false;
        }

    });

    $(".btn-removepart").click(function () {
        $(".fr-order-items-parts").attr('action', '/orderview/removepartsineditform');
        $(".fr-order-items-parts").submit();
    });
    $(".btn-removeddpart").click(function () {
        $(".fr-order-items-parts").attr('action', '/orderview/removeddparts');
        $(".fr-order-items-parts").submit();
    });

    $('.fr-orderitemspartsinaddform').submit(function () {
        if (confirm('Are you sure you want to remove selected part(s)?')) {
            var serializedForm = $(this).serialize();
            App.blockUI($('.tbl-order-items-parts'), false);
            $.ajax({
                type: 'POST',
                url: "/orderview/removepartsinaddform",
                cache: false,
                data: serializedForm,
                success: function (data) {
                    $(".tbl-order-items-parts").html(data);
                }
            });
            return false;
        } else {
            return false;
        }

    });



    $(".btn-OnHold").click(function () {
        App.blockUI($("body"));
        $("#hfactioncancel").val(2);
        $(this).attr('type', 'submit');
        $(this).trigger('click');
    });

    $(".btn-UnCancelled").click(function () {
        if (confirm('Are you sure you want to UNCANCEL this Order?')) {
            $("#hfactioncancel").val(1);
            $("#choosewarehouse").trigger("click");
        }
    });

    $(".btn-UnCancelledItem").click(function () {
        if (confirm('Are you sure you want to UNCANCEL this Item?')) {
            $("#hfactioncancel").val(1);
            $("#choosewarehouse").trigger("click");
        }
    });

    $(".fr-searchpostcode").submit(function () {
        $(".btn-selectcustomeraddres").attr("onclick", "selectedaddresspostcode()");
        if ($("#postcode").val() == "" && $("#Surname").val() == "" && $("#Email").val() == "" && $("#PreviousOrder").val() == "") {
            alert("Error: Please enter value!");
            return false;
        } else {
            App.blockUI($('body'), false);
            var serializedForm = $(this).serialize();
            var results = $(".row-customerorderaddress");
            $.ajax({
                url: "/orderview/SearchPostcode",
                data: serializedForm,
                cache: false,
                success: function (response) {
                    $("#btn-customerresult").trigger("click");
                    results.html('');
                    $.each(response, function (id, option) {
                        results.append($('<tr onclick="customeraddressselected(' + option.id + ',\'' + option.postcode + '\')">' +
                            '<td>' + option.id + '</td>' +
                            '<td>' + option.address + '</td>' +
                            '<td>' + option.email + '</td>' +
                            '</tr>'));
                    });
                    App.unblockUI($('body'));
                    $(".tbl-selected tbody tr").click(function () {
                        $(this).addClass("row-selected");
                        $(".tbl-selected tbody tr").not(this).removeClass('row-selected');
                    });
                }
            });


            //var results = $("#cbresultpostcode");
            //$.ajax({
            //    url: "/orderview/CheckPostcode",
            //    type: 'GET',
            //    data: serializedForm,
            //    cache: false,
            //    success: function (data) {
            //        if (data == "True") {
            //            $.ajax({
            //                url: "/orderview/SearchPostcode",
            //                data: serializedForm,
            //                cache: false,
            //                success: function (response) {
            //                    $(".result-postcode").show();
            //                    results.html('');
            //                    $.each(response, function (id, option) {
            //                        results.append($('<option></option>').val(option.id).html(option.name));
            //                    });
            //                    App.unblockUI($('#customerdetail'));
            //                }
            //            });
            //        } else {
            //            alert("The postcode was not recognised as a valid UK postcode and has not been checked for additional delivery costs.");
            //            App.unblockUI($('#customerdetail'));
            //        }
            //    }
            //});
        }
        return false;
    });

    $("#fr-lookuppostcode").submit(function () {
        App.blockUI($('.modal-body'), false);
        var serializedForm = $(this).serialize();
        var results = $("#lookupresult");
        $.ajax({
            url: "/orderview/LookupPostcode",
            data: serializedForm,
            cache: false,
            success: function (response) {
                results.html('');
                if (response.length == 0) {
                    alert('No Addresses Found');
                } else {
                    $.each(response, function (id, option) {
                        results.append($('<option></option>').val(option.Id).html(option.Description));
                    });
                }

                App.unblockUI($('.modal-body'));
            }
        });
        return false;
    });

    // new order seach product
    $("#fr-newordersearchproduct").submit(function () {
        var storeid = $("#StoreId").val();
        if (storeid == 0) {
            alert('Please select a store');
            return false;
        } else {
            $("#hfstoreid").val(storeid);
            App.blockUI($('#orderitem'), false);
            var serializedForm = $(this).serialize();
            var results = $("#lstorderitemproductresult");
            $.ajax({
                url: "/orderview/NewOrderSearchProduct",
                data: serializedForm + "&storeid=" + storeid,
                method: "POST",
                cache: false,
                success: function (response) {
                    results.html('');
                    if (response.length == 0) {
                        alert('Sorry no results');
                    } else {
                        $.each(response, function (id, option) {
                            results.append($('<option></option>').val(option.id).html(option.name));
                        });
                    }

                    App.unblockUI($('#orderitem'));
                }, error: function () {
                    alert('Error!');
                    App.unblockUI($('#orderitem'));
                }
            });
            return false;
        }
    });

    $(".btn-listallproducts").click(function () {
        var storeid = $("#StoreId").val();
        if (storeid == 0) {
            alert('Please select a store');
            return false;
        } else {
            $("#hfstoreid").val(storeid);
            App.blockUI($('#orderitem'), false);
            var results = $("#lstorderitemproductresult");
            $.ajax({
                url: "/orderview/NewOrderSearchProduct?productname=&storeid=" + storeid,
                method: "POST",
                cache: false,
                success: function (response) {
                    results.html('');
                    if (response.length == 0) {
                        alert('Sorry no results');
                    } else {
                        $.each(response, function (id, option) {
                            results.append($('<option></option>').val(option.id).html(option.name));
                        });
                    }

                    App.unblockUI($('#orderitem'));
                }, error: function () {
                    alert('Error!');
                    App.unblockUI($('#orderitem'));
                }
            });
            return false;
        }
    });

    $("#fr-neworderaddproducttoorder").submit(function () {
        var storeid = $("#StoreId").val();
        var postcode = $("#hfPostcode").val();
        if (storeid == 0) {
            alert('Please select a store');
            return false;
        } else {
            App.blockUI($('body'), false);
            var serializedForm = $(this).serialize();
            $.ajax({
                url: "/orderview/NewOrderAddProductToOrder",
                data: serializedForm + "&storeid=" + storeid + "&postcode=" + postcode,
                method: "POST",
                cache: false,
                success: function (data) {
                    $(".pnorderitemadded").html(data);
                    OrderItemsSummaryTemplate();
                    totalorderprice();
                    reCssorderitem();
                    App.unblockUI($('body'));
                    window.scrollTo(0, document.body.scrollHeight);
                    adiustprice();

                    $.ajax({
                        url: "/orderview/ServiceCheckAndProductInfo?productoptionid=" + $("#hfProductOptionId").val(),
                        success: function (data) {
                            $(".pnservicecheck").html(data);
                            $("#servicecheck").modal("show");
                        }
                    });
                }
            });
            return false;
        }
    });

    $("#fr-adiusprice").submit(function () {
        App.blockUI($('.modal-body'), false);
        var serializedForm = $(this).serialize();
        $.ajax({
            url: "/orderview/NewOrderAdiustPrice",
            data: serializedForm,
            method: "POST",
            cache: false,
            success: function (data) {
                $(".pnorderitemadded").html(data);
                OrderItemsSummaryTemplate();
                totalorderprice();
                App.unblockUI($('.modal-body'));
                $("#adiusprice").modal("hide");
                adiustprice();
            },
            error: function () {
                alert('Value entered is not numeric');
            }
        });
        return false;
    });

    savecustomerorderaddress();

    $("#fr-customproduct").submit(function () {
        App.blockUI($('.modal-body'), false);
        var serializedForm = $(this).serialize();
        $.ajax({
            url: "/orderview/AddCustomProduct",
            data: serializedForm,
            method: "POST",
            cache: false,
            success: function (data) {
                if (data == "error") {
                    alert("Not a valid Price");
                    App.unblockUI($('.modal-body'));
                } else {
                    $(".pnorderitemadded").html(data);
                    OrderItemsSummaryTemplate();
                    totalorderprice();
                    App.unblockUI($('.modal-body'));
                    $("#customproduct").modal("hide");
                    adiustprice();
                    window.scrollTo(0, document.body.scrollHeight);
                }
            }, error: function () {
                alert("Quantity not is number");
                App.unblockUI($('.modal-body'));
            }
        });
        return false;
    });
    $("#frEditFAQs").submit(function () {
        App.blockUI($('.modal-body'), false);
        var serializedForm = $(this).serialize();
        $.ajax({
            url: "/orderview/EditFAQ",
            data: serializedForm,
            method: "POST",
            cache: false,
            success: function (data) {
                $('#frFilterFAQs').submit();
            },
            error: function () {
                App.unblockUI($('.modal-body'));
            }
        });
        return false;
    });
    $("#customprice, #customqty").keyup(function () {
        customtotalprice();
    });

    $('#frViewTaskTypes').submit(function () {
        var serialize = $(this).serialize();
        App.blockUI($('#LstTaskTypes'));
        $.ajax({
            url: "/orderview/SaveTaskTypes",
            method: "GET",
            data: serialize,
            success: function (data) {
                if (data == '') {
                    alert("Success!");
                    LoadLstTaskTypes($("#TaskTypeId").val());
                } else alert(data);
                App.unblockUI($('#LstTaskTypes'));
            }, error: function () {
                App.unblockUI($('#LstTaskTypes'));
            }
        });
        return false;
    });

    $('#frViewTaskTitles').submit(function () {
        var serializeForm = $(this).serialize();
        App.blockUI($('#LstTaskTitles'));
        $.ajax({
            url: "/orderview/SaveTaskTitles",
            method: "GET",
            data: serializeForm,
            success: function (data) {
                if (data == '') {
                    alert("Success!");
                    LoadLstTaskTitles($("#TaskTypeId").val());
                } else alert(data);
                App.unblockUI($('#LstTaskTitles'));
            }, error: function () {
                App.unblockUI($('#LstTaskTitles'));
            }
        });
        return false;
    });

    $("#fr-orderadvancesearch").submit(function () {
        var serializeForm = $(this).serialize();
        App.blockUI($('.container-fluid'));
        $.ajax({
            url: "/orderview/advancesearch",
            method: "POST",
            data: serializeForm,
            success: function (data) {
                $(".orderadvancesearchresult").html(data);
                App.unblockUI($('.container-fluid'));
                InitDatatable();
                $(window).scrollTop($(".orderadvancesearchresult").offset().top);
            }, error: function () {
                alert('Search error');
                App.unblockUI($('.container-fluid'));
            }
        });
        return false;
    });
    $("#btn-showCommentNote").click(function () {
        $("#fr-CommentNote").slideDown(100);
        $(this).hide();
        $('.box-note .box-content').animate({
            scrollTop: 0
        }, 500);
    });
    $("#btn-hideCommentNote").click(function () {
        $("#fr-CommentNote").slideUp(100);
        $("#btn-showCommentNote").fadeIn(100);
    });
    $("#fr-CommentNote").submit(function () {
        $.ajax({
            url: "/orderview/commentcustomernote",
            data: $(this).serialize(),
            success: function (data) {
                if (data != '') {
                    alert("Error!");
                } else {
                    $('#customernote-template .ticket-comment').html($("#txtCommentNote").val());
                    $('#lstComment-Note').prepend($('#customernote-template').html());
                    $('.lstCustomerNotes').prepend(' <li style="color: rgb(0, 0, 189);">' + $("#txtCommentNote").val() + '</li>');
                    $("#btn-hideCommentNote").click();
                    $("#txtCommentNote").val('');
                }

            }, error: function () {
            }
        });
        return false;
    });
    $("#fr-refundtescoorder").submit(function () {
        if (confirm("Are you sure you want to give a refund for £" + $("#refundamount").val() + ", order " + $("#tradeorderref").val())) {
            App.blockUI($('body'));
            $.ajax({
                url: "/orderview/GiveRefundTesco",
                method: "POST",
                data: $(this).serialize() + "&tradeorderref=" + $("#tradeorderref").val(),
                success: function (data) {
                    if (data == "") {
                        location.reload();
                    } else {
                        alert(data);
                        App.unblockUI($('body'));
                    }
                }, error: function () {
                    alert("Error");
                    App.unblockUI($('body'));
                }
            });
        }
        return false;
    });
});


function adiustprice() {
    $(".btn-adiustprice").click(function () {
        var parent = $(this).parent().parent().parent();
        $("#ExistingTotalPrice").val(parent.find("span.totalorderitemprice").html());
        $("#AdiustQuantity").val("x " + parent.find("span.orderitemqty").html());
        $("#NewPrice").val(parent.find("span.orderitemprice").html());
        $("#hforderitemindex").val(parent.attr("data-id"));
        $("#hfqty").val(parent.find("span.orderitemqty").html());
        $("#adiusprice").modal("show");
    });
}

function reCssorderitem() {
    $(".pnorderitemadded fieldset").each(function (index, value) {
        //$(this).find("legend").html("Order Item " + (index + 1));
        //$(this).attr("id", "_orderitem" + (index + 1));
        if (index % 3 == 0) {
            $(this).css('margin-left', '0');
        }
    });
}

function productselected(productid) {
    var ddlProductOption = $("#productoptionid");
    $.ajax({
        cache: false,
        url: "/orderview/getproductoption",
        data: { "productid": productid },
        success: function (data) {
            ddlProductOption.html('');
            $.each(data, function (id, option) {
                ddlProductOption.append($('<option></option>').val(option.id).html(option.name));
            });
        }
    });
}

function loaditemorderparts(orderitemid, orderid, isselected) {
    if (isselected) return;
    App.blockUI($('.order-items-parts'), false);
    App.blockUI($('.action-orderitem'), false);
    $.ajax({
        url: '/orderview/LoadOrderItemAction',
        data: { orderitemid: orderitemid, orderid: orderid },
        success: function (data) {
            $(".action-orderitem").html(data);
            App.unblockUI($('.action-orderitem'));

        }
    });
    $.ajax({
        url: '/orderview/OrderItemParts',
        data: { orderitemid: orderitemid },
        success: function (res) {
            $(".order-items-parts").html(res);
            InitDatatable();
        }
    });
}

function loadtableorderitempart(orderitemid) {
    App.blockUI($('.order-items-parts'), false);
    $.ajax({
        url: '/orderview/OrderItemParts',
        data: { orderitemid: orderitemid },
        success: function (res) {
            $(".order-items-parts").html(res);
            InitDatatable();
        }
    });
}

function CheckCancelOrder(orderId) {
    $.ajax({
        url: '/orderview/CheckOrderIsInLoad',
        data: { orderId: orderId },
        success: function (data) {
            if (data == "False") {
                PopupCenter('/orderview/cancelorder?orderid=' + orderId, 780, 500);
            } else {
                alert('Please remove this order from the load first');
            }
        }
    });
}
function CheckCancelOrderItem(orderItemId) {
    $.ajax({
        url: '/orderview/CheckOrderItemIsInLoad',
        data: { orderItemId: orderItemId },
        success: function (data) {
            if (data == "False") {
                PopupCenter('/orderview/cancelorder?orderitemid=' + orderItemId, 780, 500);
            } else {
                alert('Please remove this order from the load first');
            }
        }
    });
}
function CheckParagonOrderItem(orderId, orderItemId) {
    $.ajax({
        url: '/orderview/CheckParagonOrderItem',
        data: { orderItemId: orderItemId },
        success: function (data) {
            if (data == "True") {
                PopupCenter('/orderview/deliverydate?orderid=' + orderId, 1200, 600);
            }
            else {
                PopupCenter('/orderview/overridechangedate?orderitemid=' + orderItemId + '&sendmail=true', 400, 300);
            }
        }
    });
}
function CheckAuditPickingADay(orderItemId) {
    $.ajax({
        url: '/orderview/CountAuditPickingADay',
        data: { orderItemId: orderItemId },
        success: function (data) {
            if (data > 0) {
                PopupCenter('/orderview/auditpickingaday?orderitemid=' + orderItemId, 980, 600);
            }
            else {
                alert('There is currently no audit for selecting picking a day');
            }
        }
    });
}

function newvisit(orderid) {
    var ddlvisit = $(".grouped-visit");
    $.ajax({
        cache: false,
        url: "/orderview/newvisit",
        data: { "orderid": orderid },
        success: function (data) {
            ddlvisit.html('');
            $.each(data, function (id, option) {
                ddlvisit.append($('<option></option>').val(option.id).html(option.name));
            });
        }
    });
}

function ReleaseQtyXPartnameSentstock(orderitemid, sentstockid) {
    if (confirm('Do you wish to release all held items?\nPlease click yes to release all in stock items, no if you just want to release this item')) {
        $(".order-items-parts").html("<div class='ajax-loading'></div>");
        $.ajax({
            type: 'POST',
            url: '/orderview/ReleaseQtyXPartnameSentstock',
            data: { orderitemid: orderitemid, sentstockid: sentstockid, action: 1 },
            success: function (data) {
                $(".order-items-parts").html(data);
                alert('Order Released');
            }
        });
    } else {
        $(".order-items-parts").html("<div class='ajax-loading'></div>");
        $.ajax({
            url: '/orderview/ReleaseQtyXPartnameSentstock',
            data: { orderitemid: orderitemid, sentstockid: sentstockid, action: 2 },
            success: function (data) {
                $(".order-items-parts").html(data);
                alert('Item Released');
            }
        });
    }
}

function holdpart(sentstockid, orderitempartid) {
    $(".order-items-parts").html("<div class='ajax-loading'></div>");
    $.ajax({
        url: '/orderview/holdpart',
        data: { orderitempartid: orderitempartid, sentstockid: sentstockid },
        success: function (data) {
            $(".order-items-parts").html(data);
            alert('Stock held for ' + sentstockid);
        }
    });
}

function removeFromBackOrder(orderitempartid, waitingid) {
    $(".order-items-parts").html("<div class='ajax-loading'></div>");
    $.ajax({
        url: '/orderview/removeFromBackOrder',
        data: { orderitempartid: orderitempartid, waitingid: waitingid },
        success: function (data) {
            $(".order-items-parts").html(data);
        }
    });
}

function removepartfromfeedandadd(orderitempartid) {
    $("#choosewarehouse").trigger("click");
    $(".btn-warehouse").click(function () {
        $(".close").trigger("click");
        $(".order-items-parts").html("<div class='ajax-loading'></div>");
        if (confirm('Do you want to place the other parts on hold')) {
            $.ajax({
                type: 'POST',
                url: '/orderview/RemovePartFromFeedAndAddToBackOrder',
                data: { orderitempartid: orderitempartid, action: 1, warehouseid: $("#Warehouseid").val() },
                success: function (data) {
                    $(".order-items-parts").html(data);
                }
            });
        } else {
            $.ajax({
                type: 'POST',
                url: '/orderview/RemovePartFromFeedAndAddToBackOrder',
                data: { orderitempartid: orderitempartid, action: 2, warehouseid: $("#Warehouseid").val() },
                success: function (data) {
                    $(".order-items-parts").html(data);
                }
            });
        }
    });
}

function printinvoice(orderid) {
    if (confirm('Do you want to send this through as an email to the customer instead?')) {
        window.location = "/orderview/printinvoice?orderid=" + orderid + "&ac=1";
    } else {
        window.location = "/orderview/printinvoice?orderid=" + orderid + "&ac=2";
    }
}

function photoselected(photoid) {
    $(".photodetail").html("<div class='ajax-loading'></div>");
    $.ajax({
        url: '/rdm/img',
        data: { photoid: photoid },
        success: function (data) {
            $(".photodetail").html(data);
        }
    });
}

function cancelorder(orderitemid) {
    if ($('.txt-reasoncancel').val() == '') {
        alert('Please enter Reason required!');
    } else {
        if (confirm("Are you sure you want to CANCEL this " + (orderitemid > 0 ? "Order Item" : "Order") + "?")) {
            App.blockUI($("body"));
            $("#hfactioncancel").val(3);
            $(".btn-Cancelled").trigger('click');
        }
    }

}

function cancelorderitem() {
    if ($('.txt-reasoncancel').val() == '') {
        alert('Please enter Reason required!');
    } else {
        if (confirm("Are you sure you want to CANCEL this Item?")) {
            $("#hfactioncancel").val(3);
            $('.btn-CancelledItemFirst').hide();
            $(".btn-CancelledItem").trigger('click');
        }
    }
}

function suppliercommunicationselected(orderid, companyid) {
    $(".fr-supplierresendemail").html("<div class='ajax-loading'></div>");
    $.ajax({
        url: '/orderview/GetSupplierCommunication',
        data: { orderid: orderid, companyid: companyid },
        success: function (data) {
            $(".fr-supplierresendemail").html(data);
        }
    });
}

function loghistoryselected(extrainfo, picker) {
    $("#LogHistory-ExtraInfo").html(extrainfo);
    $("#LogHistory-PickerName").val(picker);
}

function selectedaddresspostcode(customerid, postcode) {
    if (customerid == undefined) {
        alert("Please select customer!");
    } else {
        $(".close").trigger("click");
        $("#pncustomerdetail").show();
        App.blockUI($('body'), false);
        $.ajax({
            url: "/orderview/CustomerDetailsPostcode?customerid=" + customerid,
            cache: false,
            success: function (data) {
                $('#pncustomerdetail').html(data);
                $('.datetimepicker').datetimepicker({
                    language: 'en',
                    pick12HourFormat: true
                });
                $("#hfPostcode").val(postcode);
                App.unblockUI($('body'));
                appendAddressDelivery();
                savecustomerorderaddress();
                CancelCurrentVisits();
                adddeliveryitem(postcode);
            }
        });
    }
}

function adddeliveryitem(postcode) {
    $.ajax({
        url: "/orderview/adddeliveryitems?postcode=" + postcode,
        success: function (data) {
            $(".pnorderitemadded").html(data);
            reCssorderitem();
            OrderItemsSummaryTemplate();
            $(".btn-adiustprice").click(function () {
                var parent = $(this).parent().parent().parent();
                $("#ExistingTotalPrice").val(parent.find("span.totalorderitemprice").html());
                $("#AdiustQuantity").val("x " + parent.find("span.orderitemqty").html());
                $("#NewPrice").val(parent.find("span.orderitemprice").html());
                $("#hforderitemindex").val(parent.attr("data-id"));
                $("#hfqty").val(parent.find("span.orderitemqty").html());
                $("#adiusprice").modal("show");
            });
        }
    });
}

function SeparateBilling() {
    var check = $(".cbSeparate").is(":checked");
    if (check) {
        $(".seperatebilling").show();
        $("#billForename").attr("required", "required");
        $("#billSurname").attr("required", "required");
        $("#billAddressLine1").attr("required", "required");
        $("#billAddressLine2").attr("required", "required");
        $("#billTown").attr("required", "required");
        $("#billCounty").attr("required", "required");
        $("#billPostcode").attr("required", "required");
    } else {
        $(".seperatebilling").hide();
        $("#billForename").removeAttr("required");
        $("#billSurname").removeAttr("required");
        $("#billAddressLine1").removeAttr("required");
        $("#billAddressLine2").removeAttr("required");
        $("#billTown").removeAttr("required");
        $("#billCounty").removeAttr("required");
        $("#billPostcode").removeAttr("required");
    }
    appendAddressDelivery();
}

function customeraddressselected(customerid, postcode) {
    $(".btn-selectcustomeraddres").attr("onclick", "selectedaddresspostcode(" + customerid + ",'" + postcode + "')");
}

function savecustomerorderaddress() {
    $('#fr-customerorderaddress').submit(function () {
        var serializedForm = $(this).serialize();
        App.blockUI($('#pncustomerdetail'), false);
        $.ajax({
            type: 'POST',
            url: "/orderview/SaveCustomerAddress",
            data: serializedForm,
            cache: false,
            success: function (data) {
                if (data.status == true) {
                    $.ajax({
                        url: "/orderview/CustomerDetailsPostcode?customerid=" + data.customerid,
                        cache: false,
                        success: function (data) {
                            $('#pncustomerdetail').html(data);
                            appendAddressDelivery();
                            $(window).scrollTop();
                            savecustomerorderaddress();
                            adddeliveryitem($("#PostcodeShipping").val());
                        }
                    });
                    alert(data.msg);
                } else {
                    alert(data.msg);
                    App.unblockUI($('#pncustomerdetail'));
                }
                //selectedaddresslookup();
            }
        });
        return false;
    });
}

function lookuppostcode(shipping) {
    $("#hfshipping").val(shipping);
    $("#lookupresult").html('');
    $("#lookuppostcode").modal('show');
}
function selectedaddresslookup() {
    if ($("#lookupresult").val() == null) {
        alert("You must select an address");
    } else {
        var id = $("#lookupresult").val();
        id = id.toString().split('.')[0];
        App.blockUI($('#lookuppostcode'), false);
        $.ajax({
            url: "/orderview/ProcessLookupResults",
            type: "json",
            data: { postcode: $("#txtPostcodelookup").val(), id: id },
            success: function (data) {
                $("#pncustomerdetail").show();
                if ($("#hfshipping").val() == "false") {
                    $("#AddressLine1").val(data.Street);
                    $("#AddressLine2").html(data.Line2);
                    $("#Town").val(data.Town);
                    $("#County").val(data.County);
                    $("#PostcodeShipping").val(data.Postcode);
                } else {
                    $("#billAddressLine1").val(data.Street);
                    $("#billAddressLine2").html(data.Line2);
                    $("#billTown").val(data.Town);
                    $("#billCounty").val(data.County);
                    $("#billpostcode").val(data.Postcode);
                }
                App.unblockUI($('#lookuppostcode'));
                $("#lookuppostcode").modal('hide');
                appendAddressDelivery();
            }
        });
    }
}

function orderitemproductresult(productid) {
    $("#hfproductid").val(productid);
    App.blockUI($('#orderitem'), false);
    $.ajax({
        url: "/orderview/NewOrderGetProductDetail",
        data: { productid: productid, storeid: $("#hfstoreid").val() },
        cache: false,
        success: function (data) {
            $("#pnlCurrentProduct").html(data);
            App.unblockUI($('#orderitem'));
        }, error: function () {
            alert("Error!");
            App.unblockUI($('#orderitem'));
        }
    });
}

function productoptionschange(productoptionid) {
    $(".btn-pricehistory").attr("onclick", "PopupCenter('/orderview/neworderpricehistory?productoptionid=" + productoptionid + "',1200,600);")
    App.blockUI($('#pnproductoptioncontrol'), false);
    $.ajax({
        url: "/orderview/NewOrderGetSubOptionsDetail",
        data: { productoptionid: productoptionid, storeid: $("#hfstoreid").val() },
        cache: false,
        success: function (data) {
            $("#pnproductoptioncontrol").html(data);
        }
    });
}

function neworderproductsuboptionchange() {
    var currentprice = $("#hfcurrentPrice").val();
    var newPrice = "";
    $("#pnSubOptions select").each(function () {
        newPrice += "&newPrice=" + $(this).val().split("_")[1];
    });
    $.ajax({
        url: "/orderview/newordercalculatorprice?currentprice=" + currentprice + newPrice,
        cache: false,
        success: function (data) {
            $("#currentprice").val("£" + data);
        }
    });
}

function removeorderitem(orderitemid) {
    App.blockUI($('.pnorderitemadded'), false);
    $.ajax({
        url: "/orderview/removeorderitem?orderitemid=" + orderitemid,
        cache: false,
        success: function (data) {
            $(".pnorderitemadded").html(data);
            OrderItemsSummaryTemplate();
            reCssorderitem();
            totalorderprice();
            CancelCurrentVisits();
            UpdateBoxedItems();
        }
    });
}

function totalorderprice() {
    $.ajax({
        url: "/orderview/TotalOrderPrice",
        success: function (data) {
            $("#TotalOrderPrice").val(data);
            $('#TotalCost').html(data);
            totalorderitemsprice();
            totaldiscountvalue();
            adminchargevalue();
        }
    });
}
function totalorderitemsprice() {
    $.ajax({
        url: "/orderview/TotalOrderItemsPrice",
        success: function (data) {
            $('#TotalOrderItemsPrice').html(data);
        }
    });
}

function totaldiscountvalue() {
    $.ajax({
        url: "/orderview/TotalDiscountValue",
        success: function (data) {
            $('#TotalDiscountValue').html(data);
        }
    });
}

function adminchargevalue() {
    $.ajax({
        url: "/orderview/adminchargevalue",
        success: function (data) {
            $('#AdminChargeValue').html(data);
        }
    });
}

function appendAddressDelivery() {
    var shippingAddress = "";
    var billingAddress = "";
    shippingAddress = $('#title').val() + ' ' + $('#Forename').val() + ' ' + $('#shipSurname').val() + "<br>";
    shippingAddress += $('#AddressLine1').val();
    if ($('#AddressLine2').val() != "")
        shippingAddress += "<br>" + $('#AddressLine2').val();
    if ($('#Town').val() != "")
        shippingAddress += "<br>" + $('#Town').val();
    if ($('#County').val() != "")
        shippingAddress += "<br>" + $('#County').val();
    if ($('#PostcodeShipping').val() != "")
        shippingAddress += "<br>" + $('#PostcodeShipping').val();
    if ($('#Phone').val() != "")
        shippingAddress += "<br>" + $('#Phone').val();
    if ($('#Mobile').val() != "")
        shippingAddress += "<br>" + $('#Mobile').val();
    if ($('#EmailAddress').val() != "")
        shippingAddress += "<br>" + $('#EmailAddress').val();

    billingAddress = $('#billtitle').val() + ' ' + $('#billForename').val() + ' ' + $('#billSurname').val() + "<br>";
    billingAddress += $('#billAddressLine1').val();
    if ($('#billAddressLine2').val() != "")
        billingAddress += "<br>" + $('#billAddressLine2').val();
    if ($('#billTown').val() != "")
        billingAddress += "<br>" + $('#billTown').val();
    if ($('#billCounty').val() != "")
        billingAddress += "<br>" + $('#billCounty').val();
    if ($('#billPostcode').val() != "")
        billingAddress += "<br>" + $('#billPostcode').val();
    if ($('#billPhone').val() != "")
        billingAddress += "<br>" + $('#billPhone').val();
    if ($('#billMobile').val() != "")
        billingAddress += "<br>" + $('#billMobile').val();

    if (!$(".cbSeparate").is(":checked"))
        billingAddress = shippingAddress;

    $('#divContactDelivery').html(shippingAddress);
    $('#divBillingDelivery').html(billingAddress);
}

function issueVoucher() {
    var cId = $("#CustomerID").val();
    if (cId == undefined) {
        alert("Please select customer !");
    }
    else {
        $("#divIssuevoucher").modal('show');
        $("#divIssuevoucher").html("<div class='ajax-loading'></div>");
        $.ajax({
            url: '/orderview/IssueSpecialDiscountVoucher',
            data: {},
            success: function (data) {
                $("#divIssuevoucher").html(data);
                $("#divIssuevoucher").modal('show');
                $("#cId").val(cId);
                initfrIssueVoucher();
            }
        });
    }
}

function SelectDeliveryDateCheckedChange() {
    var check = $("#chkSelectDate").is(":checked");
    if (!check) {
        $("#SelectDeliveryDate").show();
        $.ajax({
            url: '/orderview/SetIsSelectOwn',
            data: { isOwn: false },
            success: function () {
            }
        });
    } else {
        $("#SelectDeliveryDate").hide();
        $.ajax({
            url: '/orderview/SetIsSelectOwn',
            data: { isOwn: true },
            success: function () {
            }
        });
    }
}

function saveIssueVoucher() {
    $('#fr-issuevoucher').submit(function () {
        $("#divIssuevoucher").html("<div class='ajax-loading'></div>");
        var serializedForm = $(this).serialize();
        $.ajax({
            type: 'POST',
            url: "/orderview/saveIssueVoucher",
            data: serializedForm,
            success: function (data) {
                $("#divIssuevoucher").modal('hide');
                $("#vouchercode").val(data);
                ChangeVoucher();
            }
        });
        return false;
    });
}

function initfrIssueVoucher() {
    try {
        $('.datetimepicker').datetimepicker({
            language: 'en'
        });
        $('#datetimepicker2, #datetimepicker3, #datetimepicker4, #datetimepicker5, .datetimepicker').datetimepicker({
            language: 'en'
        });
    } catch (e) {

    }
}



function OrderItemsSummaryTemplate() {
    $.ajax({
        url: "/orderview/TemplateOrderItemsSummary",
        success: function (data) {
            $("#divOrderitemsSummary").html(data);
        }
    });
}


function confirmorder() {
    var storeid = $("#StoreId").val();
    var postcode = $("#hfPostcode").val();
    var cId = $("#CustomerID").val();
    var totalPrice = $("#TotalOrderPrice").val();
    var payment = $("#cbpayment").val();
    var check = $("#chkAgree").is(":checked");
    var currentprice = $("#currentprice").val();
    var separate = $(".cbSeparate").is(":checked");
    var specialInstructions = $("#SpecialIns").val();

    if (storeid == 0) {
        alert('Please select a site');
        return false;
    }
    if ($(".pnorderitemadded fieldset").length == 0) {
        alert("You must add items to this order first");
        return false;
    } else {
        $.ajax({
            url: "/orderview/CheckProductOpitionExcludedAndIncluded?postcode=" + postcode,
            success: function (data) {
                if (data != "") {
                    alert(data);
                }
                return false;
            }
        });
    }
    if (cId == undefined) {
        alert("You must first save the customer details");
        return false;
    }
    if ((totalPrice == "" || totalPrice == "£0.00") && payment != "Cheque Payment") {
        alert("You cannot take a credit card order for £0. Please select Cheque Payment then Confirm the order in the pending order tab.");
        return false;
    }
    if (!check) {
        alert("Customer need to accept our term and conditions to make the purchase");
        return false;
    }

    //proccess order
    if (confirm('Are you sure all the details are correct for the order?')) {
        App.blockUI($('body'), false);
        $.ajax({
            url: "/orderview/ConfirmNewOrder",
            data: { storeid: storeid, postcode: postcode, customerid: cId, payment: payment, currentprice: currentprice, separate: separate, specialInstructions: specialInstructions },
            type: 'POST',
            success: function (data) {
                $("#paymenttaken iframe").attr("src", data.url + "?orderid=" + data.orderid + "&orderref=" + data.orderref);
                //$("#paymenttaken iframe").reload();
                App.unblockUI($('body'));
                $("#paymenttaken").modal("show");
                var title = "0";
                window.onmessage = function (e) {
                    if (e.origin !== "https://secure.kybotech.co.uk") {
                        return;
                    }
                    title = e.data;
                    $(".btn-paymentstatus").attr("onclick", "continueconfirmorder(" + title + ")");
                };

            }, error: function () {
                alert("Confirm order error!");
            }
        });
    }
}

function ChangeVoucher() {
    var cId = $("#CustomerID").val();
    var storeid = $("#StoreId").val();
    $.ajax({
        url: "/orderview/changeVoucher",
        data: { voucherCode: $('#vouchercode').val(), customerId: cId, storeId: storeid },
        success: function (data) {
            $('#divVoucherMessage').show();
            $('#divVoucherMessage').html(data);
            //$('#btnRemoveVoucher').attr('disabled', 'disabled');
            if (data == "Apply voucher success") {
                $('#btnRemoveVoucher').removeAttr('disabled');
                $('#IconVoucherInvalid').hide();
                $('#IconVoucherValid').show();
                totalorderprice();
            }
        }
    });
}

function RemoveVoucher() {
    $.ajax({
        url: "/orderview/RemoveVoucher",
        data: {},
        success: function (data) {
            $('#divVoucherMessage').hide();
            $('#btnRemoveVoucher').attr('disabled', 'disabled');
            $('#IconVoucherInvalid').show();
            $('#IconVoucherValid').hide();
            $('#vouchercode').val("");
            totalorderprice();
        }
    });
}

function AddAnFAQ() {
    $('#frEditFAQs').html("<div class='ajax-loading'></div>");
    $.ajax({
        url: "/orderview/AddFAQ",
        data: { faqId: $('#SelectedFAQId').val(), siteId: $('#SiteId').val(), productId: $('#ProductId').val(), companyId: $('#CompanyID').val() },
        success: function (data) {
            $('#frEditFAQs').html(data);
        }
    });
    $('#EditFAQModal').modal();
}
function EditAnFAQ() {
    var faqId = $('#SelectedFAQId').val();
    if (faqId == 0) {
        alert('Please select an FAQ');
        return;
    }
    $('#frEditFAQs').html("<div class='ajax-loading'></div>");
    $.ajax({
        url: "/orderview/EditFAQ",
        data: { faqid: faqId },
        success: function (data) {
            $('#frEditFAQs').html(data);
        }
    });
    $('#EditFAQModal').modal();
}
function DeleteAnFAQ() {
    var faqId = $('#SelectedFAQId').val();
    if (faqId == 0) {
        alert('Please select an FAQ');
        return;
    }
    if (confirm("Are you sure you want to delete this FAQ?")) {
        $.ajax({
            url: "/orderview/DeleteFAQ",
            data: { faqid: faqId },
            success: function (data) {
                $('#frFilterFAQs').submit();
            }
        });
    }
}
function SelectedProductFAQChanged(productId) {
    App.blockUI($('.modal-body'), false);
    $.ajax({
        url: "/orderview/GetListStoreFAQ",
        data: { companyId: 0, productId: productId },
        success: function (data) {
            var i = 0;
            $("#SiteID").html('');
            $.each(data, function (id, option) {
                if (i == 1) $("#SiteID").append($('<option selected="selected"></option>').val(option.Id).html(option.Name));
                else $("#SiteID").append($('<option ></option>').val(option.Id).html(option.Name));
                i++;
            });
        }
    });
    $.ajax({
        url: "/orderview/GetListCompanyFAQ",
        data: { siteId: 0, productId: productId },
        success: function (data) {
            var i = 0;
            $("#CompanyID").html('');
            $.each(data, function (id, option) {
                if (i == 1) $("#CompanyID").append($('<option selected="selected"></option>').val(option.Id).html(option.Name));
                else $("#CompanyID").append($('<option ></option>').val(option.Id).html(option.Name));
                i++;
            });
            App.unblockUI($('.modal-body'), false);
        }
    });
}
function SelectedSupplierFAQChanged(companyId) {
    App.blockUI($('.modal-body'), false);
    $.ajax({
        url: "/orderview/GetListStoreFAQ",
        data: { companyId: companyId, productId: 0 },
        success: function (data) {
            var i = 0;
            $("#SiteID").html('');
            $.each(data, function (id, option) {
                if (i == 1) $("#SiteID").append($('<option selected="selected"></option>').val(option.Id).html(option.Name));
                else $("#SiteID").append($('<option ></option>').val(option.Id).html(option.Name));
                i++;
            });
        }
    });
    $.ajax({
        url: "/orderview/GetListProductFAQ",
        data: { companyId: companyId, siteId: 0 },
        success: function (data) {
            var i = 0;
            $("#ProductID").html('');
            $.each(data, function (id, option) {
                if (i == 1) $("#ProductID").append($('<option selected="selected"></option>').val(option.Id).html(option.Name));
                else $("#ProductID").append($('<option ></option>').val(option.Id).html(option.Name));
                i++;
            });
            App.unblockUI($('.modal-body'), false);
        }
    });
}
function SelectedStoreFAQChanged(siteId) {
    App.blockUI($('.modal-body'), false);
    $.ajax({
        url: "/orderview/GetListCompanyFAQ",
        data: { siteId: siteId, productId: 0 },
        success: function (data) {
            var i = 0;
            $("#CompanyID").html('');
            $.each(data, function (id, option) {
                if (i == 1) $("#CompanyID").append($('<option selected="selected"></option>').val(option.Id).html(option.Name));
                else $("#CompanyID").append($('<option ></option>').val(option.Id).html(option.Name));
                i++;
            });
        }
    });
    $.ajax({
        url: "/orderview/GetListProductFAQ",
        data: { companyId: 0, siteId: siteId },
        success: function (data) {
            var i = 0;
            $("#ProductID").html('');
            $.each(data, function (id, option) {
                if (i == 1) $("#ProductID").append($('<option selected="selected"></option>').val(option.Id).html(option.Name));
                else $("#ProductID").append($('<option ></option>').val(option.Id).html(option.Name));
                i++;
            });
            App.unblockUI($('.modal-body'), false);
        }
    });
}
function DisplayFAQ() {
    var faqId = $('#SelectedFAQId').val();
    if (faqId == 0) {
        alert('Please select an FAQ');
        return;
    }
    if (confirm("Are you sure you wish to display FAQ number " + faqId + " on the website?")) {
        $.ajax({
            url: "/orderview/DisplayFAQ",
            data: { faqid: faqId },
            success: function (data) {
                $('#msg-ViewFAQs').html(data);
            }
        });
    }
}
function DoNotDisplayFAQ() {
    var faqId = $('#SelectedFAQId').val();
    if (faqId == 0) {
        alert('Please select an FAQ');
        return;
    }
    if (confirm("Are you sure you wish to stop displaying FAQ number " + faqId + " on the website?")) {
        $.ajax({
            url: "/orderview/DoNotDisplayFAQ",
            data: { faqid: faqId },
            success: function (data) {
                $('#msg-ViewFAQs').html(data);
            }
        });
    }
}
function PopularAnswerFAQ() {
    var faqId = $('#SelectedFAQId').val();
    if (faqId == 0) {
        alert('Please select an FAQ');
        return;
    }
    if (confirm("Are you sure you wish to mark FAQ number " + faqId + " as a popular answer?")) {
        $.ajax({
            url: "/orderview/PopularAnswerFAQ",
            data: { faqid: faqId },
            success: function (data) {
                $('#msg-ViewFAQs').html(data);
            }
        });
    }
}
function NotPopularAnswerFAQ() {
    var faqId = $('#SelectedFAQId').val();
    if (faqId == 0) {
        alert('Please select an FAQ');
        return;
    }
    if (confirm("Are you sure you wish to un-mark FAQ number " + faqId + " as a popular answer?")) {
        $.ajax({
            url: "/orderview/NotPopularAnswerFAQ",
            data: { faqid: faqId },
            success: function (data) {
                $('#msg-ViewFAQs').html(data);
            }
        });
    }
}
function SetSelectedStore(value) {
    $.ajax({
        url: "/orderview/SetSelectedStore",
        data: { storeId: value },
        success: function (data) {
        }
    });
}

function SelectedVisitChanged(orderCode, isVisit, visitnum, visitdate) {
    $("#selectedOrderCode").html(orderCode);
    $("#selectedVisitNum").val(visitnum);
    $("#selectedVisitCode").val(orderCode);
    $("#txtReasonForRemoveVisit").val();
    $("#IsSelectedVisitTree").val(isVisit);
    $("#selectedVisitDate").val(visitdate);
    $.ajax({
        url: "/orderview/GetVisitInfo",
        data: { orderCode: orderCode },
        success: function (data) {
            $("#VisitDetail").html(data);
            $("#datetimepicker1").datetimepicker({
                language: 'en',
                startDate: '-1d'
            });
            InitfrmGetAvailableDate_Submit();
            InitfrChangeVisitInfo_Submit();
        }
    });
}
function SelectedUngroupItemChanged(orderItemId) {
    $.ajax({
        url: "/orderview/SetSelectedUngroupItem",
        data: { orderItemId: orderItemId },
        success: function (data) {
        }
    });
}
function SelectedGroupedItemChanged(sku, quantity) {
    $.ajax({
        url: "/orderview/SetSelectedProdVisitItem",
        data: { sku: sku, quantity: quantity },
        success: function (data) {

        }
    });
}


function CheckBeforeSelectDate() {
    $.ajax({
        url: "/orderview/CheckBeforeSelectDate",
        data: {
            specialInstructions: $("#SpecialIns").text, title: $("#title").val(),
            firstName: $("#Forename").val(), surname: $("#shipSurname").val(), addressLine1: $("#AddressLine1").val(),
            addressLine2: $("#AddressLine2").val(), postcode: $("#PostcodeShipping").val(), storeId: $("#StoreId").val()
        },
        success: function (data) {
            if (data == "") {
                var child = PopupCenter('/orderview/SelectDeliveryDate', 1200, 650);
                //child.onbeforeunload = function() {
                //    ConfirmAfterSelectDate();

                //};
                var timer = setInterval(checkChild, 500);
                function checkChild() {
                    if (child != undefined && child.closed) {
                        clearInterval(timer);
                        ConfirmAfterSelectDate();
                    }
                }
            } else {
                alert(data);
            }
        }
    });
}
function ConfirmAfterSelectDate() {
    $.ajax({
        url: "/orderview/ConfirmAfterSelectDeliveryDate",
        success: function (data) {
            totalorderprice();
            UpdateDeliveryInfo();
        }
    });
}
function SelectDeliveryDate() {
    var cId = $("#CustomerID").val();
    var storeid = $("#StoreId").val();
    var postcode = $("#postcode").val();
    if (cId == null || cId == undefined) {
        alert("Please select customer !");
    }
    else {
        $('#divSelectDeliveryDate').modal('show');
        $.ajax({
            url: "/orderview/SelectDeliveryDate",
            data: { customerId: cId, storeId: storeid, postcode: postcode },
            success: function (data) {
                initfrIssueVoucher();
                $('#divSelectDeliveryDate').html(data);
            }
        });
    }
}
function continueconfirmorder(status) {
    if (status != undefined && status != "1") {
        if (confirm('The payment is failed or not completed, do you still want to close the screen?')) {
            $("#paymenttaken").modal("hide");
            App.blockUI($('body'), false);
            $.ajax({
                url: "/orderview/ContiuneConfirmNewOrder?paymenttaken=false&vipstatusid=" + $("#VipStatusId").val(),
                type: "POST",
                success: function (data) {
                    $("body").append("<script>" + data + "</script>");
                }
            });
        }
    } else {
        $("#paymenttaken").modal("hide");
        App.blockUI($('body'), false);
        $.ajax({
            url: "/orderview/ContiuneConfirmNewOrder?paymenttaken=true&vipstatusid=" + $("#VipStatusId").val(),
            type: "POST",
            success: function (data) {
                $("body").append("<script>" + data + "</script>");
            }
        });
    }
    App.unblockUI($('body'));
}
function checkpostcodeservice() {
    var postcode = $("#postcodeService").val();
    if (postcode.length <= 5) {
        alert("Postcode invalid");
    } else {
        App.blockUI($('.pnservicecheck'), false);
        $.ajax({
            url: "/orderview/checkpostcodeservice?postcode=" + postcode + "&productoptionid=" + $("#hfProductOptionId").val(),
            success: function (data) {
                App.unblockUI($('.pnservicecheck'));
                if (data.status == true) {
                    $(".assemblyservice").show();
                    $(".assemblyservice input").show();
                    $(".assemblyservice .assemblyname").html(data.msg);
                } else {
                    $(".assemblyservice").show();
                    $(".assemblyservice input").hide();
                    $(".assemblyservice .assemblyname").html(data.msg);
                }
            }
        });
    }

}
function addassemblyservice() {
    App.blockUI($('body'), false);
    $.ajax({
        url: "/orderview/AddAssemblyService",
        success: function (data) {
            $(".pnorderitemadded").html(data);
            $("#servicecheck").modal("hide");
            OrderItemsSummaryTemplate();
            totalorderprice();
            reCssorderitem();
            App.unblockUI($('body'));
            window.scrollTo(0, document.body.scrollHeight);
            adiustprice();
        }
    });
}
function SelectedBoxItemChanged(orderItemId) {
    $.ajax({
        url: "/orderview/SetSelectedBoxItem",
        data: { orderItemId: orderItemId },
        success: function (data) {
            $("#VisitDetail").html(data);
            $("#datetimepicker1").datetimepicker({
                language: 'en',
                pick12HourFormat: true
            });
            InitfrmSelectBoxDeliveryDate_Submit();
        }
    });
}
function SelectedAvaibleDateChanged(date) {
    $.ajax({
        url: "/orderview/SetSelectedBookingWindow",
        data: { date: date },
        success: function (data) {
            $("#SelectedTimeSlot").html(date);
        }
    });
}
function AddNewVisit() {
    $.ajax({
        url: "/orderview/AddNewVisit",
        success: function (data) {
            window.location = "/orderview/SelectDeliveryDate?refresh=true";
        }
    });
}
function RemoveVisit() {
    if ($('#IsSelectedVisitTree').val() == 0) {
        alert("Please select visit!");
        return;
    }

    if ($('#selectedVisitNum').val() > 0) {
        $('#ReasonForRemoveVisit').modal();
        $('#ActionReasonForRemoveVisit').val('RemoveVisit');
        return;
    }
    $.ajax({
        url: "/orderview/RemoveVisit",
        data: { reason: $('#txtReasonForRemoveVisit').val() },
        success: function (data) {
            window.location = "/orderview/SelectDeliveryDate?refresh=true";
        }
    });
}
function AutoGroupItems() {
    $.ajax({
        url: "/orderview/AutoGroupItems",
        success: function (data) {
            window.location = "/orderview/SelectDeliveryDate?refresh=true";
        }
    });
}
function DeleteVisitItem() {
    $.ajax({
        url: "/orderview/DeleteVisitItem",
        success: function (data) {
            window.location = "/orderview/SelectDeliveryDate?refresh=true";

        }
    });
}
function AddItemToVisit() {
    $.ajax({
        url: "/orderview/CheckVisitIsReserved",
        success: function (data) {
            var action = true;
            if (data != "") {
                if (!confirm(data)) {
                    action = false;
                }
            }
            if (action) {
                $.ajax({
                    url: "/orderview/AddItemToVisit",
                    success: function () {
                        window.location = "/orderview/SelectDeliveryDate?refresh=true";
                    }
                });
            }
        }
    });
}
function InitfrmGetAvailableDate_Submit() {

    $("#frmGetAvailableDate").submit(function () {
        if ($("#selectedVisitCode").val() == "") {
            alert("Please select visit!");
            return false;
        }
        App.blockUI($("#VisitDetail"));
        $.ajax({
            url: "/orderview/GetAvaibleDates",
            data: $(this).serialize(),
            success: function (msg) {
                if (msg != "") {
                    alert(msg);
                    App.unblockUI($("#VisitDetail"));
                } else {
                    $.ajax({
                        url: "/orderview/GetListAvaibleDates",
                        success: function (data) {
                            $("#ListAvailableDate").html(data);
                            App.unblockUI($("#VisitDetail", false));
                        },
                        error: function () {
                            alert("Failed to load the booking windows");
                            App.unblockUI($("#VisitDetail", false));
                        }
                    });
                }
            }, error: function () {
                alert("Failed to load the booking windows");
                App.unblockUI($("#VisitDetail", false));
            }
        });
        return false;
    });
}
function InitfrmSelectBoxDeliveryDate_Submit() {

    $("#frmSelectBoxDeliveryDate").submit(function () {
        App.blockUI($("#VisitDetail"));
        $.ajax({
            url: "/orderview/SetDeliveryDateBoxItem",
            method: "POST",
            data: $(this).serialize(),
            success: function (msg) {
                if (msg != "") {
                    alert(msg);
                } else {
                    alert("Delivery date has been changed!");
                    window.location = "/orderview/SelectDeliveryDate?refresh=true";
                }
                App.unblockUI($("#VisitDetail", false));
            }, error: function () {
                alert("Failed to change delivery date");
                App.unblockUI($("#VisitDetail", false));
            }
        });
        return false;
    });
}
function InitfrChangeVisitInfo_Submit() {
    $("#frChangeVisitInfo").submit(function () {
        if ($("#selectedVisitCode").val() == "") {
            alert("Please select visit!");
            return false;
        }
        App.blockUI($("#VisitDetail"));
        $.ajax({
            url: "/orderview/ChangeVisitDetail",
            data: $(this).serialize(),
            success: function (msg) {
                if (msg != "") {
                    alert(msg);
                    App.unblockUI($("#VisitDetail"));
                } else {
                    $("#divVisitInfo").css("background", "none");
                    alert("Visit info has been changed!");
                    App.unblockUI($("#VisitDetail"));
                }
            }, error: function () {
                alert("Failed to change visit info");
                App.unblockUI($("#VisitDetail", false));
            }
        });
        return false;
    });
}
function SelectAvailableDate() {

    if ($("#selectedVisitCode").val() == "") {
        alert("Please select visit!");
        return;
    }
    if ($('#selectedVisitNum').val() > 0 && $("#selectedVisitDate").val() != "") {
        $('#ReasonForRemoveVisit').modal();
        $('#ActionReasonForRemoveVisit').val('SelectAvailableDate');
        return;
    }

    App.blockUI($("#VisitDetail"));
    $.ajax({
        url: "/orderview/SelectAvailableDate",
        data: { reason: $('#txtReasonForRemoveVisit').val() },
        success: function (msg) {
            if (msg != "") {
                alert(msg);
                App.unblockUI($("#VisitDetail"));
            } else {
                alert("Delivery date has been changed!");
                window.location = "/orderview/SelectDeliveryDate?refresh=true";
            }
        }, error: function () {
            alert("Failed to select date");
            App.unblockUI($("#VisitDetail", false));
        }
    });
}

function ConfirmReasonForRemoveVisit() {
    if ($('#txtReasonForRemoveVisit').val() == "") {
        alert("Please enter reason!");
        return;
    }
    $('#selectedVisitNum').val(0);
    if ($('#ActionReasonForRemoveVisit').val() == 'SelectAvailableDate') {
        SelectAvailableDate();
    }
    if ($('#ActionReasonForRemoveVisit').val() == 'RemoveVisit') {
        RemoveVisit();
    }
}
function SaveSpecialInstruction(specialInstructions) {

    if ($("#selectedVisitCode").val() == "") {
        alert("Please select visit!");
        return;
    }
    App.blockUI($("#VisitDetail"));
    $.ajax({
        url: "/orderview/SaveSpecialInstruction",
        data: { specialInstructions: specialInstructions },
        success: function () {
            alert("Special instruction has been changed!");
            App.unblockUI($("#VisitDetail", false));
        }, error: function () {
            alert("Failed to select date");
            App.unblockUI($("#VisitDetail", false));
        }
    });
}
function VisitInfoChanged() {
    $("#divVisitInfo").css("background", "antiquewhite");
}
function CancelCurrentVisits() {
    $.ajax({
        url: "/orderview/CancelCurrentVisits",
        success: function (data) {
        }
    });
}

function UpdateBoxedItems() {
    $.ajax({
        url: "/orderview/UpdateBoxedItems",
        success: function (data) {
        }
    });
}
function UpdateDeliveryInfo() {
    OrderItemsSummaryTemplate();
    $.ajax({
        url: "/orderview/GetLnkDeliveryDate",
        success: function (data) {
            if (data != '') {
                $('#SelectDeliveryDate').html(data);
            }
        }
    });
    $.ajax({
        url: "/orderview/GetLbDeliveryCosts",
        success: function (data) {
            $('#DeliveryCosts').html(data);
        }
    });
    $.ajax({
        url: "/orderview/GetSpecialInstruction",
        success: function (data) {
            $('#SpecialIns').html(data);
        }
    });

}
function ClearAll() {
    $.ajax({
        url: "/orderview/ClearAll",
        success: function (data) {
            window.location = "/orderview/neworder";
        }
    });

}

function addnewcustomer() {
    $("#customerresult").modal("hide");
    $("#lookupresult").html('');
    $("#lookuppostcode").modal('show');
    $(".btn-selectedaddresslookup").attr('onclick', 'selectaddressnewcustomer()');
}

function selectaddressnewcustomer() {
    if ($("#lookupresult").val() == null) {
        alert("You must select an address");
    } else {
        var id = $("#lookupresult").val();
        id = id.toString().split('.')[0];
        App.blockUI($('#lookuppostcode'), false);
        $.ajax({
            url: "/orderview/ProcessLookupResults",
            type: "json",
            data: { postcode: $("#txtPostcodelookup").val(), id: id },
            success: function (data) {
                $("#AddressLine1").val(data.Street);
                $("#billAddressLine1").val(data.Street);
                $("#AddressLine2").val(data.Line2);
                $("#billAddressLine2").val(data.Line2);
                $("#Town").val(data.Town);
                $("#billTown").val(data.Town);
                $("#County").val(data.County);
                $("#billCounty").val(data.County);
                $("#PostcodeShipping").val(data.Postcode);
                $("#billPostcode").val(data.Postcode);
                $("#pncustomerdetail").show();
                $(".btn-selectedaddresslookup").attr('onclick', 'selectedaddresslookup()');
                App.unblockUI($('#lookuppostcode'));
                $("#lookuppostcode").modal('hide');
            }
        });
    }
}

function addcustomproduct() {
    var storeid = $("#StoreId").val();
    if (storeid == 0) {
        alert('Please select a store');
    } else {
        if (confirm("You can now adjust a price of an item once you have added it to the order.\n\n" +
            "Only add custom products if the product you require does not exist on\n the database and " +
            "you have checked with the buyers that it won't be added.\n\nAre you sure you want to add a custom Product?")) {
            $("#customproduct").modal("show");
        }
    }
}

function pendingphoneorderselected(temporaryId, orderid) {
    $("#btn-cancelorder").attr("onclick", "pendingphoneordercancel('" + temporaryId + "','" + orderid + "')");
    $("#btn-confirmorder").attr("onclick", "pendingphoneorderconfirm('" + temporaryId + "','" + orderid + "')");
}

function pendingphoneordercancel(temporaryId, orderid) {
    if (temporaryId == "0") {
        alert("Please select a order");
    } else {
        if (confirm("Are you sure you want to cancel order:" + temporaryId + "?")) {
            App.blockUI($('body'), false);
            $.ajax({
                url: "/orderview/pendingphoneordercancel?temporaryId=" + orderid,
                method: "POST",
                success: function (data) {
                    alert(data);
                    App.unblockUI($('body'));
                    location.reload();
                }
            });
        }
    }
}

function pendingphoneorderconfirm(temporaryId, orderid) {
    if (temporaryId == "0") {
        alert("Please select a order");
    } else {
        if (confirm("This will send this order to the Supplier and a confirmation email to the Customer. Order No: " + temporaryId + "?")) {
            App.blockUI($('body'), false);
            $.ajax({
                url: "/orderview/pendingphoneorderconfirm?temporaryId=" + orderid,
                method: "POST",
                success: function (data) {
                    alert(data);
                    App.unblockUI($('body'));
                    location.reload();
                }
            });
        }
    }
}
function ShowAllTitleType(taskTypeId) {
    LoadLstTaskTypes(taskTypeId);
    LoadLstTaskTitles(taskTypeId);
}
function LoadLstTaskTypes(taskTypeId) {
    var showAll = 0;
    if ($("#ShowAll").is(':checked')) showAll = 1;
    App.blockUI($('#LstTaskTypes'));
    $('#LstTaskTypes').html("");
    $.ajax({
        url: "/orderview/GetAllTaskTypes?showAll=" + showAll,
        method: "GET",
        success: function (data) {
            taskTypeId = taskTypeId == 0 ? data[0].TaskTypeID : taskTypeId;
            $.each(data, function (id, option) {
                $('#LstTaskTypes').append($("<tr onclick = 'SelectedLstTaskTypesChanged(" + option.TaskTypeID + ",\"" + option.TaskType + "\"," + option.TTOrder + ")' class='" + (option.TaskTypeID == taskTypeId ? "row-selected" : "") + "'>" +
                                "<td>" + option.TaskType + "</td>" +
                                "<td>" + option.TTOrder + "</td>" +
                                "<td><input type='checkbox' name='TaskTypeVisible' onchange='SetTaskTypeVisible(" + option.TaskTypeID + ", $(this).is(\":checked\"))' value='" + option.TaskTypeID + "' " + (option.Visible == true ? "checked=checked" : "") + "/></td>" +
                                "</tr>"));
                if (option.TaskTypeID == taskTypeId) {
                    SelectedLstTaskTypesChanged(option.TaskTypeID, option.TaskType, option.TTOrder);
                }
            });
            $("#LstTaskTypes tr").click(function () {
                $(this).addClass("row-selected");
                $("#LstTaskTypes  tr").not(this).removeClass('row-selected');
            });
            App.unblockUI($('#LstTaskTypes'));
        }
    });
}
function SelectedLstTaskTypesChanged(taskTypeId, tasktype, order) {
    LoadLstTaskTitles(taskTypeId);
    $('#TaskTypeId').val(taskTypeId);
    $('#TaskType').val(tasktype);
    $('#TTOrder').val(order);
    $('#submitType').html('Save');
}
function SelectedLstTaskTitleChanged(taskTitleId, taskTitle, assignToGroup) {
    $('#TaskTitleId').val(taskTitleId);
    $('#TaskTitle').val(taskTitle);
    $('#AssignToGroupId').val(assignToGroup);
    $('#submitTitle').html('Save');
}
function LoadLstTaskTitles(taskTypeId) {
    App.blockUI($('#LstTaskTitles'));
    $('#LstTaskTitles').html("");
    $.ajax({
        url: "/orderview/GetAllTaskTitles",
        method: "GET",
        data: { taskTypeId: taskTypeId },
        success: function (data) {
            $.each(data, function (id, option) {
                $('#LstTaskTitles').append($("<tr onclick ='SelectedLstTaskTitleChanged(" + option.TaskTitleID + ",\"" + option.TaskTitle + "\"," + option.AssignToGroupID + ")' class='" + (id == 0 ? "row-selected" : "") + "'>" +
                                "<td>" + option.TaskTitle + "</td>" +
                                "<td>" + option.AssignToGroupID + "</td>" +
                                "<td><input type='checkbox' name='TaskTitleVisible' onchange='SetTaskTitleVisible($(\"#TaskTypeId\").val()," + option.TaskTitleID + ",$(\"#TTOrder\").val(),$(this).is(\":checked\"))' value='" + option.TaskTitleID + "' " + (option.TaskTypeTitleID == 1 ? "checked=checked" : "") + "/></td>" +
                                "</tr>"));
            });
            $("#LstTaskTitles  tr").click(function () {
                $(this).addClass("row-selected");
                $("#LstTaskTitles  tr").not(this).removeClass('row-selected');
            });
            SelectedLstTaskTitleChanged(data[0].TaskTitleID, data[0].TaskTitle, data[0].AssignToGroupID);
            App.unblockUI($('#LstTaskTitles'));
        }
    });
}
function SetTaskTypeVisible(taskTypeId, visible) {
    App.blockUI($('#LstTaskTypes'));
    $.ajax({
        url: "/orderview/SetTaskTypeVisible",
        method: "GET",
        data: { taskTypeId: taskTypeId, visible: visible },
        success: function (data) {
            if (data == '') {
            } else alert(data);
            App.unblockUI($('#LstTaskTypes'));
        }, error: function () {
            App.unblockUI($('#LstTaskTypes'));
        }
    });
}
function SetTaskTitleVisible(taskTypeId, taskTitleId, TTOrder, visible) {
    App.blockUI($('#LstTaskTitles'));
    $.ajax({
        url: "/orderview/SetTaskTitleVisible",
        method: "GET",
        data: { taskTypeId: taskTypeId, taskTitleId: taskTitleId, TTOrder: TTOrder, visible: visible },
        success: function (data) {
            if (data == '') {
            } else alert(data);
            App.unblockUI($('#LstTaskTitles'));
        }, error: function () {
            App.unblockUI($('#LstTaskTitles'));
        }
    });
}

function customtotalprice() {
    var price = $("#customprice").val();
    var qty = $("#customqty").val();
    if (isNaN(price)) {
        alert("Price invalid!");
    } else if (isNaN(qty)) {
        alert("Quantity invalid!");
    } else {
        $.ajax({
            url: "/orderview/mathdecimal",
            data: { price: price, qty: qty },
            success: function (data) {
                $("#customtotalprice").val(data);
            }
        });
    }
}
function checkaddtaskrequirederr(selector) {
    selector.removeClass("addtask-required-warring");
    var err = false;
    if (selector.val() == 0 || selector.val() == "") {
        selector.addClass("addtask-required-warring");
        err = true;
    }
    return err;
}
function checkaddtaskerr() {
    var err = false;
    err = checkaddtaskrequirederr($("#TaskTypeID")) || err;
    err = checkaddtaskrequirederr($("#TaskTitleID")) || err;
    err = checkaddtaskrequirederr($("#ReasonID")) || err;
    err = checkaddtaskrequirederr($("#CompleteByHrs")) || err;
    err = checkaddtaskrequirederr($("#PriorityID")) || err;
    err = checkaddtaskrequirederr($("#AssignedToUser")) || err;
    if ($("#AssignedToUser").val() == 267) {
        err = checkaddtaskrequirederr($("#OrderStatusID")) || err;
        err = checkaddtaskrequirederr($("#RefundReasonID")) || err;
    }
    if ($("#AssignedToUser").val() == 754) {
        err = checkaddtaskrequirederr($("#AgentsIssueID")) || err;
        err = checkaddtaskrequirederr($("#TriggerStatementID")) || err;
        err = checkaddtaskrequirederr($("#DispositionID")) || err;
    }
    $("#TaskDescription").removeClass("addtask-required-warring");
    if ($("#TaskDescription").val() == "") {
        $("#TaskDescription").addClass("addtask-required-warring");
        err = true;
    }

    if (err) {
        alert("Some field has not been filled. Check and fill it, please!");
    }
    else $('#frAddTask').submit();
}

function createrdmfromitem(orderItemId) {
    App.blockUI($("#lstorder-items"));
    $.ajax({
        url: "/orderview/CheckOrderItemIsboxOutsock",
        method: "GET",
        data: { orderItemId: orderItemId },
        success: function (msg) {
            if (msg != "") {
                if (!confirm(msg)) {
                    App.unblockUI($("#lstorder-items"));
                    return;
                }
            }
            $.ajax({
                url: "/orderview/CheckOrderHasRdm",
                method: "GET",
                data: { orderItemId: orderItemId },
                success: function (msg) {
                    if (msg != "") {
                        if (!confirm(msg)) {
                            App.unblockUI($("#lstorder-items"));
                            return;
                        }
                    }
                    $.ajax({
                        url: "/orderview/CheckOrderItemIsQuestionnaire",
                        method: "GET",
                        data: { orderItemId: orderItemId },
                        success: function (data) {
                            if (data == "True") {
                                PopupCenter('/rdm/addquestionnaireform?orderitemid=' + orderItemId, 700, 640);
                            } else PopupCenter('/rdm/addquestionnairenonfac?orderitemid=' + orderItemId, 700, 640);
                            App.unblockUI($("#lstorder-items"));
                        },
                        error: function () {
                            App.unblockUI($("#lstorder-items"));
                            alert("error!");
                        }
                    });
                },
                error: function () {
                    App.unblockUI($("#lstorder-items"));

                    alert("error!");
                }
            });
        }
    });
}

function checkorderisinparagon(orderref) {
    App.blockUI($("#lstorder-items"));
    $.ajax({
        url: "/orderview/CheckOrderIsInParagonSever",
        method: "GET",
        data: { orderref: orderref },
        success: function (data) {
            if (data == "True") {
                alert(orderref + " is already exists in paragon system.");
            } else
                alert(orderref + " is not exists in paragon system.");

            App.unblockUI($("#lstorder-items"));
        },
        error: function () {
            App.unblockUI($("#lstorder-items"));
            alert("error!");
        }
    });
}

function SIAddTo(to) {
    var originalNew = $(".originalNew").val();
    var original = $("#original");
    if (to == "top") {
        if (originalNew != "") {
            original.val(originalNew + "\n" + original.val());
        }
    } else if (to == "bottom") {
        if (originalNew != "") {
            original.val(original.val() + "\n" + originalNew);
        }
    }
    $(".originalNew").val("");
}

function sortloghistory(cell) {
    var sort = cell.attr('data-sort');
    if (sort == "asc") {
        cell.attr('data-sort', 'desc');
    } else {
        cell.attr('data-sort', 'asc');
    }
    App.blockUI($(".loghistorydetail"), false);
    $.ajax({
        url: "/orderview/sortloghistory",
        data: { col: cell.html(), sort: sort, orderid: $("#orderid").val() },
        success: function (data) {
            $('.bodyloghistory').html(data);
            App.unblockUI($(".loghistorydetail"));
        }
    });

}

function sortemailhistory(cell) {
    var sort = cell.attr('data-sort');
    if (sort == "asc") {
        cell.attr('data-sort', 'desc');
    } else {
        cell.attr('data-sort', 'asc');
    }
    App.blockUI($(".email-history"), false);
    $.ajax({
        url: "/orderview/sortemailhistory",
        data: { col: cell.html(), sort: sort, orderid: $("#orderid").val() },
        success: function (data) {
            $('.bodyemail-history').html(data);
            App.unblockUI($(".email-history"));
        }
    });

}

function cancellationschange(userid) {
    if (userid == 267) {
        $(".cancellationsshow").show("fast");
        $(".resolutionshow").hide("fast");
    } else if (userid == 754) {
        $(".resolutionshow").show("fast");
        $(".cancellationsshow").hide("fast");
    } else {
        $(".resolutionshow").hide("fast");
        $(".cancellationsshow").hide("fast");
    }
}
function taskorderstatuschange(statusid) {
    $.ajax({
        url: "/orderview/taskorderstatuschange?statusid=" + statusid,
        success: function (data) {
            $("#RefundReasonID").html("");
            $.each(data, function (id, option) {
                $("#RefundReasonID").append($('<option></option>').val(option.id).html(option.name));
            });
        }
    });
}

function ViewDeliveryFile(host, path) {
    $('#SelectedDeliveryFileName').val(path);
    ViewOrderDeliveryFile(path);
}
function ViewOrderDeliveryFile(path) {
    var host = "/stockfile/DeliveryNoteFiles/";
    $('#ifViewPDF').attr("src", host + path.replace("%5c%5ckybotech.local%5cdfs%5cpublic%5cIT%5cStock+Control%5cDeliveryNoteFiles%5c", ""));
}
function ViewOrderDeliveryFolder(folder, orderref) {
    App.blockUI($("#lstOrderDeliveryFile"), false);
    $.ajax({
        url: "/orderview/ManagerOrderDeliveryFiles",
        data: { folder: folder, orderref: orderref },
        success: function (data) {
            $('#lstOrderDeliveryFile').html(data);
            $("#lstOrderDeliveryFile .DeliveryFileItem").click(function () {
                $(this).addClass("selected");
                $("#lstOrderDeliveryFile .DeliveryFileItem").not(this).removeClass('selected');
            });
            App.unblockUI($("#lstOrderDeliveryFile"));
        }
    });
}

function DeleteDeliveryFile() {

    if (!confirm("Are you sure to remove ?")) {
        return;
    }
    var selectedFileName = $("#SelectedDeliveryFileName").val();
    var orderitemId = $("#orderitemid").val();
    if (selectedFileName == "") {
        alert('Please select file'); return;
    }
    $.ajax({
        url: "/orderview/DeleteDeliveryFile",
        data: { filename: selectedFileName, orderitemId: orderitemId },
        success: function (data) {
            if (data != "") {
                alert(data);
            }
            else window.location = "/Orderview/ManagerDeliveryFiles?orderitemId=" + orderitemId;
        }
    });
}

function AddToSelectedFolder(loadcode) {
    var selectedFileName = $("#SelectedDeliveryFileName").val();
    var orderref = $("#SelectedOrderRef").val();
    if (orderref == "") {
        alert('Please select order'); return;
    }

    $.ajax({
        url: "/orderview/AddToSelectedorder",
        data: { selectedFileName: selectedFileName, orderref: orderref, loadcode: loadcode },
        success: function (data) {
            ViewOrderDeliveryFolder($("#FolderPath").val(), orderref);
            $('#lstDeliveryFile .DeliveryFileItem[data-path="' + selectedFileName + '"]').remove();
        }
    });
}


function DeleteOrderDeliveryFile(selectedFileName) {
    var orderref = $("#SelectedOrderRef").val();
    if (!confirm("Are you sure to remove ?")) {
        return;
    }
    var orderitemId = $("#orderitemid").val();
    if (selectedFileName == "") {
        alert('Please select file'); return;
    }
    $.ajax({
        url: "/orderview/DeleteDeliveryFile",
        data: { filename: selectedFileName, orderitemId: orderitemId },
        success: function (data) {
            ViewOrderDeliveryFolder($("#FolderPath").val(), orderref);
        }
    });
}

function displayrefunrequest(requestid) {
    var orderid = $("#SelectedOrderId").val();
    App.blockUI($("body"));
    var fullorpartial = $(".cbfullrefund").is(":checked") ? "displayfullrefund" : "displaypartialrefund";
    $.ajax({
        url: "/orderview/" + fullorpartial + "?orderid=" + orderid + "&requestid=" + requestid,
        success: function (data) {
            if (data == "") {
                alert("the order is not cancelled yet, so full refund is not allowable. Please cancel the order first.");
                $(".cbpartialrefund").prop('checked', true);
            } else {
                $(".refundrequestcontent").html(data);
                initsubmitrefundrequest();
            }
            App.unblockUI($("body"));
        }, error: (function () {
            alert("Error!");
            App.unblockUI($("body"));
        })
    });
}

function initsubmitrefundrequest() {
    var countpartialsubmit = 0;
    $('.datetimepicker').datetimepicker({
        language: 'en',
        pick12HourFormat: true
    });
    $("#frPartialRefundRequest").submit(function () {
        $.ajax({
            url: "/orderview/savePartialRefundRequest?amountOfRefund=" + $("#txtPartialAmoundRefunded").val(),
            data: $(this).serialize(),
            success: function (data) {
                countpartialsubmit++;
                //displayrefunrequest();
                $(".hfrefundrequestid").val(data);
                $("#frUploadPhotoRefund").submit();
                $("#frPartialRefundPriceTextList").submit();
                $("#frRefundQuestionTextList").submit();
                $("#frRefundQuestioCheckList").submit();
            }, error: (function () {
                alert("Error!");
            })
        }); return false;
    });
    $("#frFullRefundRequest").submit(function () {
        var product = $("#txtProduct").val();
        product = product == "" ? "" : product + "|";
        $.ajax({
            url: "/orderview/saveFullRefundRequest",
            data: $(this).serialize() + "&product=" + product + "&amount=" + $("#txtamount").val(),
            success: function (data) {
                countpartialsubmit++;
                $(".hfrefundrequestid").val(data);
                $("#frRefundQuestionTextList").submit();
                $("#frRefundQuestioCheckList").submit();
                $("#frFullRefundQuestionCheck").submit();
            }, error: (function () {
                alert("Error!");
            })
        }); return false;
    });
    $("#frPartialRefundPriceTextList").submit(function () {
        $.ajax({
            url: "/orderview/SaveRefundTextList",
            data: $(this).serialize(),
            success: function (data) {
                countpartialsubmit++;
                if (countpartialsubmit == 4) {
                    alert("Save successfull");
                    window.close();
                }
            }, error: (function () {
                alert("Error!");
            })
        }); return false;
    });
    $("#frUploadPhotoRefund").submit(function () {
        var formData = new FormData($("#frUploadPhotoRefund")[0]);
        $.ajax({
            url: "/orderview/SaveRefundPhoto",
            type: 'POST',
            data: formData,
            async: false,
            cache: false,
            contentType: false,
            processData: false,
            success: function (data) {
            }, error: (function () {
                alert("Error!");
            })
        }); return false;
    });
    $("#frRefundQuestionTextList").submit(function () {
        $.ajax({
            url: "/orderview/SaveRefundTextList",
            data: $(this).serialize(),
            success: function (data) {
                countpartialsubmit++;
                if (countpartialsubmit == 4) {
                    alert("Save successfull");
                    window.close();
                }
            }, error: (function () {
                alert("Error!");
            })
        }); return false;
    });
    $("#frRefundQuestioCheckList").submit(function () {
        $.ajax({
            url: "/orderview/SaveRefundCheckList",
            data: $(this).serialize(),
            success: function (data) {
                countpartialsubmit++;
                if (countpartialsubmit == 4) {
                    alert("Save successfull");
                    window.close();
                }
            }, error: (function () {
                alert("Error!");
            })
        });
        return false;
    });

    $("#frFullRefundQuestionCheck").submit(function () {
        $.ajax({
            url: "/orderview/SaveRefundCheck",
            data: $(this).serialize(),
            success: function (data) {
                countpartialsubmit++;
                if (countpartialsubmit == 4) {
                    alert("Save successfull");
                    window.close();
                }
            }, error: (function () {
                alert("Error!");
            })
        });
        return false;
    });

}

function submitrefund() {
    if (confirm("Are you sure the information is correctly given?")) {
        App.blockUI($("body"));
        if ($(".cbfullrefund").is(":checked")) {
            $("#frFullRefundRequest").submit();
        } else {
            $("#frPartialRefundRequest").submit();
        }
    }
}

function ChangePendingRefund(refundRequestId) {
    if (confirm("Are you sure you want to change the request status from Awaiting DD confirmation to Pending Refund?")) {
        $.ajax({
            url: '/OrderView/ChangePendingRefund?refundrequestid=' + refundRequestId,
            success: function () {
                location.reload();
            }
        });
    }
}
function ChangeAwaitingCollectionToPendingRefund(refundRequestId) {
    if (confirm("Are you sure you want to change the request status from Awaiting Collection to Pending Refund?")) {
        $.ajax({
            url: '/OrderView/ChangePendingRefund?refundrequestid=' + refundRequestId,
            success: function () {
                location.reload();
            }
        });
    }
}
function filterLogHistoryByType(typeid) {
    $(".bodyloghistory tr").each(
        function () {
            if (typeid == 0 || $(this).data("type") == typeid) {
                $(this).show();
            } else {
                $(this).hide();
            }
        });
}

function removeloaditemonorderview(orderitemid) {
    //$("#ChooseReason").modal("show");
    //$("#hf-orderitemid").val(orderitemid);
    if (confirm('Are you sure you want to remove item from load?')) {
        App.blockUI($('.page-content'));
        $.ajax({
            url: "/load/RemoveLoadItem",
            data: { orderitemid: orderitemid, reasonid: 9, isSendMail: false },
            cache: false,
            success: function(response) {
                if (response == "") {
                    alert("Remove success!");
                } else {
                    alert(response);
                }
                App.unblockUI($('.page-content'));
            },
            error: (function() {
                alert("Error!");
                App.unblockUI($('.page-content'));
            })
        });
        return false;
    }
}

function tescorefundselected(orderitemid, orderid) {
    $.ajax({        
        url: "/orderview/RefundTescoDetail",
        data:{orderitemid:orderitemid, orderid:orderid},
        success:function(data) {
            $(".refundtescodetail").html(data);
        }, error:function() {
            alert("Error");
        }
    });
}